package org.skipper.douyin.util;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import okhttp3.*;
import okio.ByteString;
import org.skipper.douyin.domain.PushFrame;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author shoujian
 * Date: 2024-03-22
 * Time: 16:47
 */
public class DouyinWsUtil {

    private static String ttwid;

    public static void parseLiveRoomUrl(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("authority", "live.douyin.com")
                .addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("cache-control", "max-age=0")
                .addHeader("cookie", "xgplayer_user_id=251959789708; passport_assist_user=Cj1YUtyK7x-Br11SPK-ckKl61u5KX_SherEuuGPYIkLjtmV3X8m3EU1BAGVoO541Sp_jwUa8lBlNmbaOQqheGkoKPOVVH42rXu6KEb9WR85pUw4_qNHfbcotEO-cml5itrJowMBlYXDaB-GDqJwNMxMElMoZUycGhzdNVAT4XxCJ_74NGImv1lQgASIBA3Iymus%3D; n_mh=nNwOatDm453msvu0tqEj4bZm3NsIprwo6zSkIjLfICk; LOGIN_STATUS=1; store-region=cn-sh; store-region-src=uid; sid_guard=b177a545374483168432b16b963f04d5%7C1697713285%7C5183999%7CMon%2C+18-Dec-2023+11%3A01%3A24+GMT; ttwid=1%7C9SEGPfK9oK2Ku60vf6jyt7h6JWbBu4N_-kwQdU-SPd8%7C1697721607%7Cc406088cffa073546db29932058720720521571b92ba67ba902a70e5aaffd5d6; odin_tt=1f738575cbcd5084c21c7172736e90f845037328a006beefec4260bf8257290e2d31b437856575c6caeccf88af429213; __live_version__=%221.1.1.6725%22; device_web_cpu_core=16; device_web_memory_size=8; live_use_vvc=%22false%22; csrf_session_id=38b68b1e672a92baa9dcb4d6fd1c5325; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%7D; __ac_nonce=0658d6780004b23f5d0a8; __ac_signature=_02B4Z6wo00f01Klw1CQAAIDAXxndAbr7OHypUNCAAE.WSwYKFjGSE9AfNTumbVmy1cCS8zqYTadqTl8vHoAv7RMb8THl082YemGIElJtZYhmiH-NnOx53mVMRC7MM8xuavIXc-9rE7ZEgXaA13; webcast_leading_last_show_time=1703765888956; webcast_leading_total_show_times=1; webcast_local_quality=sd; xg_device_score=7.90435294117647; live_can_add_dy_2_desktop=%221%22; msToken=sTwrsWOpxsxXsirEl0V0d0hkbGLze4faRtqNZrIZIuY8GYgo2J9a0RcrN7r_l179C9AQHmmloI94oDvV8_owiAg6zHueq7lX6TgbKBN6OZnyfvZ6OJyo2SQYawIB_g==; tt_scid=NyxJTt.vWxv79efmWAzT2ZAiLSuybiEOWF0wiVYs5KngMuBf8oz5sqzpg5XoSPmie930; pwa2=%220%7C0%7C1%7C0%22; download_guide=%223%2F20231228%2F0%22; msToken=of81bsT85wrbQ9nVOK3WZqQwwku95KW-wLfjFZOef2Orr8PRQVte27t6Mkc_9c_ROePolK97lKVG3IL5xrW6GY6mdUDB0EcBPfnm8-OAShXzlELOxBBCdiQYIjCGpQ==; IsDouyinActive=false; odin_tt=7409a7607c84ba28f27c62495a206c66926666f2bbf038c847b27817acbdbff28c3cf5930de4681d3cfd4c1139dd557e; ttwid=1%7C9SEGPfK9oK2Ku60vf6jyt7h6JWbBu4N_-kwQdU-SPd8%7C1697721607%7Cc406088cffa073546db29932058720720521571b92ba67ba902a70e5aaffd5d6")
                .addHeader("referer", "https://live.douyin.com/721566130345?cover_type=&enter_from_merge=web_live&enter_method=web_card&game_name=&is_recommend=&live_type=game&more_detail=&room_id=7317569386624125734&stream_type=vertical&title_type=&web_live_tab=all")
                .addHeader("upgrade-insecure-requests", "1")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0")
                // 其他头部信息
                .build();

        try (Response response = client.newCall(request).execute()) {
            // 获取响应头部中的所有 Set-Cookie 字段
            List<String> setCookieHeaders = response.headers("Set-Cookie");

            // 获取 ttwid Cookie 的值
            ttwid = extractCookieValue(setCookieHeaders, "ttwid");

            // 输出 ttwid Cookie 的值
            System.out.println("ttwid Cookie value: " + ttwid);
            // 处理响应数据，提取所需信息
            // 这里省略了对 responseData 的处理

            // 模拟解析得到的数据
//            ttwid = "your_ttwid";
//            liveRoomId = "your_liveRoomId";
//            liveRoomTitle = "your_liveRoomTitle";

            // 构建 WebSocket URL

            // 调用 WebSocket 启动方法
            wssServerStart("959233519440");
        }
    }

    public static void wssServerStart(String liveRoomId) {
        String webSocketUrl = "wss://webcast3-ws-web-lq.douyin.com/webcast/im/push/v2/?app_name=douyin_web" +
                "&version_code=180800&webcast_sdk_version=1.3.0&update_version_code=1.3.0&compress=gzip" +
                "&internal_ext=internal_src:dim|wss_push_room_id:" + liveRoomId + "|wss_push_did:7188358506633528844" +
                "|dim_log_id:20230521093022204E5B327EF20D5CDFC6|fetch_time:1684632622323|seq:1|wss_info:0-1684632622323-0-0" +
                "|wrds_kvs:WebcastRoomRankMessage-1684632106402346965_WebcastRoomStatsMessage-1684632616357153318" +
                "&cursor=t-1684632622323_r-1_d-1_u-1_h-1&host=https://live.douyin.com&aid=6383&live_id=1&did_rule=3" +
                "&debug=false&maxCacheMessageNumber=20&endpoint=live_pc&support_wrds=1&im_path=/webcast/im/fetch/" +
                "&user_unique_id=7188358506633528844&device_platform=web&cookie_enabled=true&screen_width=1440" +
                "&screen_height=900&browser_language=zh&browser_platform=MacIntel&browser_name=Mozilla" +
                "&browser_version=5.0%20(Macintosh;%20Intel%20Mac%20OS%20X%2010_15_7)%20AppleWebKit" +
                "/537.36%20(KHTML,%20like%20Gecko)%20Chrome/113.0.0.0%20Safari/537.36&browser_online=true" +
                "&tz_name=Asia/Shanghai&identity=audience&room_id=" + liveRoomId + "&heartbeatDuration=0&signature=00000000";


        OkHttpClient client = new OkHttpClient.Builder()
                // 添加自定义请求头
                .addInterceptor(chain -> {
                    Request request = chain.request().newBuilder()
                            .addHeader("cookie", "ttwid=" + ttwid)
                            .addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
                            // 可以添加更多的请求头
                            .build();
                    return chain.proceed(request);
                })
                .build();

        Request request = new Request.Builder()
                .url(webSocketUrl)
                .build();

        WebSocketListener webSocketListener = new WebSocketListener() {
            @FXML
            private Label welcomeText;

            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                // WebSocket 连接已打开
                System.out.println("WebSocket opened");
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString text) {
                System.out.println("Received message: " + text);
                PushFrame pushFrame = (PushFrame) deserializeObject(text.toByteArray());
                welcomeText.setText("Received message: " + text);
                // 接收到文本消息
            }

            // 将二进制数据反序列化为对象
            public Object deserializeObject(byte[] data) {
                try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
                     ObjectInputStream ois = new ObjectInputStream(bis)) {
                    return ois.readObject();
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
            }


            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                // WebSocket 连接失败
                t.printStackTrace();
            }
        };

        WebSocket webSocket = client.newWebSocket(request, webSocketListener);

        // 可以添加更多的初始化和配置代码

        // 等待 WebSocket 连接成功，或者可以使用异步方法进行操作
        try {
            TimeUnit.SECONDS.sleep(35); // 5 秒后关闭 WebSocket 连接
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        webSocket.close(1000, "Connection closed");


//        try {
//            WebSocketClient ws = new WebSocketClient(new URI(webSocketUrl)) {
//
//                @FXML
//                private Label welcomeText;
//                @Override
//                public void onOpen(ServerHandshake handshakedata) {
//                    System.out.println("Connected to server: " + handshakedata);
//                }
//
//                @Override
//                public void onMessage(String message) {
//                    welcomeText.setText("Received message: " + message);
//                    System.out.println("Received message: " + message);
//                    // Implement your message handling logic here
//                }
//
//                @Override
//                public void onClose(int code, String reason, boolean remote) {
//                    System.out.println("Connection closed, code: " + code + ", reason: " + reason);
//                }
//
//                @Override
//                public void onError(Exception ex) {
//                    ex.printStackTrace();
//                }
//            };
//
//            ws.connect();
//
//        } catch (URISyntaxException e) {
//            e.printStackTrace();
//        }
    }

    private void sendAck(WebSocket ws, int logId, String internalExt) {
//        PushFrame obj = PushFrame.builder()
//                .payloadType("ack")
//                .logId(logId)
//                .setPayloadType(internalExt)
//                .build();
//        byte[] data = obj.toByteArray();
//        ws.send(data, WebSocket.ABNF.OPCODE_BINARY);
//        System.out.println("[sendAck] [🌟发送Ack] [房间Id：" + liveRoomId + "] ====> 房间标题【" + liveRoomTitle + "  】");
    }

    private byte[] decompress(byte[] compressedData) {
        try {
            GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            gzipInputStream.close();
            byteArrayOutputStream.close();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
    }

    private static String extractCookieValue(List<String> cookies, String cookieName) {
        for (String cookie : cookies) {
            String[] parts = cookie.split(";");
            for (String part : parts) {
                String trimmedPart = part.trim();
                if (trimmedPart.startsWith(cookieName + "=")) {
                    return trimmedPart.substring(cookieName.length() + 1); // 返回 key=value 中的 value
                }
            }
        }
        return null; // 没有找到对应的 Cookie
    }

}
